export function loadMore(element,callback){
    //防抖 节流
    let timer;
   element.addEventListener('scroll',function(){
       timer&&clearTimeout(timer);
       timer = setTimeout(function(){
        let clientHeight = element.clientHeight;//div的高度，可视区域 的高度
        let scrollTop = element.scrollTop;//向上卷去的高度 
        let scrollHeight = element.scrollHeight;//内容 高度
        if(clientHeight + scrollTop+10 >= scrollHeight){
           callback();
        }
       },300);
       
   });
}

export function downRefresh(element,callback){
    let startY;//按下时候的初始纵坐标
    let distance;//一共下拉的距离
    let originalTop = element.offsetTop;//最初的元素距离 父级顶部的距离
    element.addEventListener('touchstart',function(event){
        if(element.offsetTop == originalTop &&element.scrollTop == 0){
         startY = event.touches[0].pageY;
         element.addEventListener('touchmove',touchMove);
         element.addEventListener('touchend',touchEnd);
        }
    });
    function touchMove(event){
      let pageY  = event.touches[0].pageY;
      if(pageY>startY){
         distance = pageY - startY;
         element.style.top = (originalTop+distance)+'px';
      }else{
         element.removeEventListener('touchmove',touchMove);
         element.removeEventListener('touchend',touchEnd);
      }
    }
    function touchEnd(event){
     element.removeEventListener('touchmove',touchMove);
     element.removeEventListener('touchend',touchEnd);
     let timer = setInterval(function(){
         if(distance < 1){
             element.style.top =  originalTop+'px';
             clearInterval(timer);
         }else{
             element.style.top =  (originalTop+--distance)+'px';
         }
     },13);
     if(distance>10){
         callback();
     }
    }
 }

 export default class Utils {
     /**
      * 底部 navbar 高度
      */
    static BOTTOM_NAV_HEIGHT = 50;
    /*
    * 获取url参数
    * @param name 参数名称
    */
    static getQueryString( name ) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
        let r = window.location.search.substr(1).match(reg)
        if (r != null) {
            return unescape(r[2])
        }
        return null
    }
    /**
     * 深度拷贝对象,创建新对象
     * @param source 输入对象
     */
    static deepCopy( source ) {
        let result={}
        for (let key in source) {
            result[key] = source[key]
        } 
        return result
    }
        /**
     * 浏览器窗口大小相关
     */
    /**
     * 获取浏览器窗口大小
     * @returns { width: 窗口宽, height: 窗口高 }
     */
    static viewport() {
        if (document.compatMode === 'BackCompat') {
            return {
                width: document.body.clientWidth,
                height: document.body.clientHeight
            };
        } else {
            return {
                width: document.documentElement.clientWidth,
                height: document.documentElement.clientHeight
            };
        }
    }
    /**
     * 获取某元素距离文档的距离
     * @param element 元素对象
     * @returns 高度
     */
    static elementTop(element) {
        let actualTop = element.offsetTop;
        let current = element.offsetParent;
        while (current !== null) {
            actualTop += current.offsetTop;
            current = current.offsetParent;
        }
        return actualTop;
    }
    /**
     * 获取元素距离文档左侧的距离
     * @param element 元素对象
     * @returns 左侧距离
     */
    static elementLeft(element) {
        let actualLeft = element.offsetLeft;
        let current = element.offsetParent;
        while (current !== null) {
            actualLeft += current.offsetLeft;
            current = current.offsetParent;
        }
        return actualLeft;
    }
    /**
     * 获取元素相对文档位置
     * @param element 元素对象
     * @returns { offsetX:X, offsetY:Y }
     */
    static offsetViewport(element) {
        // x
        let x = Unit.elementLeft(element);
        // y
        let y = Unit.elementTop(element);
        
        let offsetX = x - window.pageXOffset;
        
        let offsetY = y - window.pageYOffset;

        return {
            offsetX: offsetX,
            offsetY: offsetY
        };
    }
    /**
     * 微信分享相关
     */
    static shares = null;
    /**
    * 分享按钮点击事件
    */
    static shareHref(msg) {
        return new Promise((res, rej) => {
            if (!window["plus"]) {
                console.log("plus 未就绪");
                rej("plus 未就绪");
                return;
            }
            if (Utils.shares) {
                Utils.shareUI(msg)
                .then(res)
                .catch(rej);
            } else {
                Utils.updateSerivces()
                .then(() => {
                    Utils.shareUI(msg)
                    .then(res)
                    .catch(rej);
                })
                .catch((e) => {
                    console.warn(e);
                    rej(e);
                })
            }
        });
    }   
    static shareUI(msg) {
        var ids = [{
            id: "weixin", 
            ex: "WXSceneSession"  /*微信好友*/
        }, {
            id: "weixin",
            ex: "WXSceneTimeline" /*微信朋友圈*/
        }],
        bts = [{
            title: "发送给微信好友"
        }, {
            title: "分享到微信朋友圈"
        }];
        return new Promise((res, rej) => {
            plus.nativeUI.actionSheet({
                    cancel: "取消",
                    buttons: bts
                },
                function(e) {
                    var i = e.index;
                    if (i > 0) {
                        console.log(ids[i - 1].id, ids[i - 1].ex);
                        Utils.shareAction(ids[i - 1].id, ids[i - 1].ex, msg)
                        .then(res)
                        .catch(rej);
                    }
                }
            );
        })
    }  
    static shareAction(id, ex, msg) {
        return new Promise((res, rej) => {
            var s = null;
            if (!id || !Utils.shares || !(s = Utils.shares[id])) {
                console.log("无效的分享服务！");
                rej("无效的分享服务！");
                return;
            }
            if (s.authenticated) {
                console.log("---已授权---");
                Utils.shareMessage(s, ex, msg)
                .then(res)
                .catch(rej);
            } else {
                console.log("---未授权---");
                s.authorize(function() {
                    Utils.shareMessage(s, ex, msg)
                    .then(res)
                    .catch(rej);
                }, function(e) {
                    console.log("认证授权失败");
                    rej("认证授权失败");
                });
            }
        });
    }

    // http://www.html5plus.org/doc/zh_cn/share.html
    static shareMessage(s, ex, msg) {
        return new Promise((res, rej) => {
            var msgMode = {
                href: msg.href,
                title: msg.title,
                content: msg.content,
                thumbs: [msg.thumb],
                pictures: [msg.picture],
                extra: {
                    scene: ex
                }
            };
            s.send(msgMode, function() {
                // console.log("分享成功!");
                res(true);
            }, function(e) {
                // console.log("分享失败!" + e);
                rej(e);
            });
        });
    }
    // update 
    static updateSerivces() {
        return new Promise((res, rej) => {
            if (!window["plus"]) {
                console.log("plus 未就绪");
                rej("plus 未就绪");
                return;
            }
            plus.share.getServices(function(s) {
                Utils.shares = {};
                for (var i in s) {
                    var t = s[i];
                    Utils.shares[t.id] = t;
                }
                res();
                console.log("获取分享服务列表成功");
            }, function(e) {
                console.log("获取分享服务列表失败：" + e.message);
                rej("获取分享服务列表失败：" + e.message);
            });
        });
    }
    /**
     * 第三方登录相关
     */
    static _auths = null;
    // weixin user info
    static _weixinUserInfo = null;
    // qq user info
    static _qqUserInfo = null;
    /**
     * 授权登录
     * qq 数据： {"target":
     *              {
     *                  "id":"qq",
     *                  "description":"QQ",
     *                  "authResult":{"ret":0,"openid":"","access_token":"","pay_token":"","expires_in":7776000,"pf":"","pfkey":"","msg":"","login_cost":234,"query_authority_cost":322,"authority_cost":3841},
     *                  "userInfo":{"ret":0,"msg":"","is_lost":0,"nickname":"","gender":"","province":"","city":"","year":"","constellation":"","figureurl":"","figureurl_1":"http://qzapp.qlogo.cn/qzapp/1104455702/23888B6528C1D4D950E0B62FFA5356D6/50","figureurl_2":"","figureurl_qq_1":"","figureurl_qq_2":"","is_yellow_vip":"0","vip":"0","yellow_vip_level":"0","level":"0","is_yellow_year_vip":"0","headimgurl":""}
     *              }
     *          }
     * @param {*} type weixin/qq/sinaweibo
     */
    static authLogin(type) {
        return new Promise((res, rej) => {
            Utils.getAuths()
            .then((auths) => {
                var s;
                for (var i = 0; i < auths.length; i++) {
                    if (auths[i].id == type) {
                        s = auths[i];
                        break;
                    }
                }
                if (!s.authResult) {
                    // 获取 qq 登陆 openid.
                    // http://ask.dcloud.net.cn/question/58510
                    s.login(function(e) {
                        console.log("登录认证成功！");
                        if (type == 'qq') {
                            console.log("qq 认证成功数据");
                            console.log(JSON.stringify(e));
                            // ios qq auth info
                            // {"target":{"id":"qq","description":"QQ","authResult":{"scope":"snsapi_userinfo","expires_in":7776000,"access_token":"","openid":""}}}
                            // android qq 和 ios qq 数据不一样。需要判断
                            if (e.target.userInfo) {
                                Utils._qqUserInfo = e;
                                res(e);
                            } else {
                                Utils.authUserInfo(type)
                                .then((userInfo) => {
                                    // res(userInfo);
                                    // {"target":{"id":"qq","description":"QQ","authResult":{"scope":"snsapi_userinfo","expires_in":7774649,"access_token":"","openid":""},"userInfo":{"figureurl":"","province":"","openid":"","figureurl_qq_1":"","nickname":"","yellow_vip_level":"0","constellation":"","city":"","year":"","figureurl_1":"","figureurl_2":"","gender":"","level":"0","is_yellow_year_vip":"0","headimgurl":"","is_lost":0,"ret":0,"vip":"0","figureurl_qq_2":"","msg":"","is_yellow_vip":"0"}}}
                                    console.log("qq 用户数据数据");
                                    console.log(JSON.stringify(userInfo));
                                    Utils._qqUserInfo = userInfo;
                                    res(userInfo);
                                })
                                .catch(rej);
                            }
                        } else if (type == 'weixin') {
                            Utils.authUserInfo(type)
                            .then((userInfo) => {
                                Utils._weixinUserInfo = userInfo;
                                res(userInfo); 
                            })
                            .catch(rej);
                        } else {
                            rej("不支持的登录方式");
                        }
                    }, function(e) {
                        console.log("登录认证失败！");
                        rej(e);
                    });
                } else {
                    console.log("已经登录认证！");
                    // rej("已经登录认证！");
                    if (type == 'qq') {
                        res(Utils._qqUserInfo);
                    } else {
                        res(Utils._weixinUserInfo);
                    }
                }
            })
            .catch((e) => {
                console.log(e);
                rej(e);
            })
        });
    }

    // 注销
    static authLogout() {
        Utils.getAuths()
        .then((auths) => {
            for (var i in auths) {
                var s = auths[i];
                if (s.authResult) {
                    s.logout(function(e) {
                        console.log("注销登录认证成功！");
                    }, function(e) {
                        console.log("注销登录认证失败！");
                    });
                }
            }
        })
        .catch((e) => {
            console.log("e");
        })
    }

    // 微信登录认证信息
    /**
     * weixin info {"openid":"","nickname":"","sex":1,"language":"","city":"","province":"","country":"","headimgurl":"","privilege":[],"unionid":""}
     * @param {*} type 
     */
    static authUserInfo(type) {
        return new Promise((res, rej) => {
            Utils.getAuths()
            .then((auths) => {
                var s;
                for (var i = 0; i < auths.length; i++) {
                    if (auths[i].id == type) {
                        s = auths[i];
                        break;
                    }
                }
                if (!s.authResult) {
                    console.log("未授权登录！");
                    rej("未授权登录！");
                } else {
                    // console.log("authUserInfo service");
                    // console.log(JSON.stringify(s));
                    s.getUserInfo(function(e) {
                        var josnStr = JSON.stringify(s.userInfo);
                        var jsonObj = s.userInfo;
                        res(jsonObj);
                        // console.log("获取用户信息成功：" + josnStr);
                    }, function(e) {
                        // console.log("获取用户信息失败：" + e.message + " - " + e.code);
                        rej("获取用户信息失败：" + e.message + " - " + e.code);
                    });
                }
            })
            .catch((e) => {
                rej(e);
            })
        });
    }
    static getAuths() {
        return new Promise((res, rej) => {
            if (Utils.auths) {
                res(Utils.auths);
            } else {
                Utils.updateAuthService()
                .then(res)
                .catch(rej);
            }
        });
    }
    static updateAuthService() {
        return new Promise((res,rej) => {
            if (!window["plus"]) {
                rej("plus 未准备好");
            }
            plus.oauth.getServices(function(services) {
                Utils._auths = services;
                res(services);
            }, function(e) {
                console.log("获取登录服务列表失败：" + e.message + " - " + e.code);
                rej("获取登录服务列表失败：" + e.message + " - " + e.code);
            });
        })
    }
    /**
     * 获取 client id
     *  plus 未准备好 返回空字符
     */
    static _clientInfo = null;
    static getClientInfo() {
        if (Utils._clientInfo != null) return Utils._clientInfo;
        // plus 未准备好
        if (!window["plus"]) return null;

        Utils._clientInfo = plus.push.getClientInfo();
        return Utils._clientInfo;
    }
    static getClientId() {
        return Utils.getClientInfo() ? Utils.getClientInfo().clientid : "";
    }
    /**
     * 获取系统图片相关
     */
    static pickImageFiles() {
        return new Promise((res, rej) => {
            // plus 未准备好
            if (!window["plus"]) rej("plus 未准备好");
            plus.gallery.pick(res,
                rej,
                {
                    multiple: true, 
                    maximum:5
                }
             );
        });
    }
    /**
     * 
     * @param {*} path  html5plus filepath
     */
    static resolveLocalFileSystemURL(path) {
        return new Promise((res, rej) => {
            // plus 未准备好
            if (!window["plus"]) rej("plus 未准备好");
            plus.io.resolveLocalFileSystemURL(path, function(entry) {
                res(entry)
           }, function(e) {
                rej(e);
           });
        })
    }
    /**
     * 
     * @param {*} file html5plus entry 对象
     */
    static getFileFromeEntry(entry) {
        return new Promise((res, rej) => {
            if (entry.file)
                entry.file(res, rej);
            else 
                rej();
        });
    }
    /**
     * 
     * @param {*} entry html5plus entry 对象
     */

    static readFileAsDataURL(entry) {
        return new Promise((res, rej) => {
            // plus 未准备好
            if (!window["plus"]) rej("plus 未准备好");

            var fileReader = new plus.io.FileReader();
            fileReader.readAsDataURL(entry);

            fileReader.onloadend = res;
            fileReader.onerror = rej;
        });
    }
}